<template>
  <Layout>
    <div class="customer-groups-container">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="box-card">
            <template #header>
              <div class="card-header">
                <span>客户分组</span>
                <el-button type="primary" @click="handleAddGroup"
                  >新增分组</el-button
                >
              </div>
            </template>

            <div class="group-list">
              <el-menu
                :default-active="activeGroupId.toString()"
                class="group-menu"
                @select="handleSelectGroup"
              >
                <el-menu-item
                  v-for="group in groupList"
                  :key="group.id"
                  :index="group.id.toString()"
                >
                  <div class="group-item">
                    <span>{{ group.name }}</span>
                    <span class="group-count">({{ group.count }})</span>
                  </div>
                </el-menu-item>
              </el-menu>
            </div>
          </el-card>
        </el-col>

        <el-col :span="18">
          <el-card class="box-card">
            <template #header>
              <div class="card-header">
                <span>{{ currentGroup ? currentGroup.name : "全部客户" }}</span>
                <div class="header-actions">
                  <el-button @click="handleEditGroup" :disabled="!currentGroup"
                    >编辑分组</el-button
                  >
                  <el-button
                    type="danger"
                    @click="handleDeleteGroup"
                    :disabled="!currentGroup"
                    >删除分组</el-button
                  >
                </div>
              </div>
            </template>

            <div class="search-bar">
              <el-form
                :inline="true"
                :model="searchForm"
                class="demo-form-inline"
              >
                <el-form-item label="客户名称">
                  <el-input
                    v-model="searchForm.name"
                    placeholder="请输入客户名称"
                    clearable
                  />
                </el-form-item>
                <el-form-item label="手机号码">
                  <el-input
                    v-model="searchForm.phone"
                    placeholder="请输入手机号码"
                    clearable
                  />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="handleSearch"
                    >查询</el-button
                  >
                  <el-button @click="resetSearch">重置</el-button>
                </el-form-item>
              </el-form>
            </div>

            <el-table
              v-loading="loading"
              :data="customerList"
              style="width: 100%"
              border
            >
              <el-table-column type="selection" width="55" />
              <el-table-column prop="name" label="客户名称" />
              <el-table-column prop="phone" label="手机号码" />
              <el-table-column prop="memberLevel" label="会员等级" />
              <el-table-column prop="totalAmount" label="累计消费">
                <template #default="scope">
                  <span>¥{{ scope.row.totalAmount.toFixed(2) }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="orderCount" label="订单数" />
              <el-table-column prop="registerTime" label="注册时间" />
              <el-table-column label="操作" width="120">
                <template #default="scope">
                  <el-button
                    type="danger"
                    link
                    @click="handleRemoveFromGroup(scope.row)"
                    >移出分组</el-button
                  >
                </template>
              </el-table-column>
            </el-table>

            <div class="pagination-container">
              <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[10, 20, 50, 100]"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 分组编辑对话框 -->
      <el-dialog
        v-model="dialogVisible"
        :title="dialogType === 'add' ? '新增客户分组' : '编辑客户分组'"
        width="40%"
      >
        <el-form :model="groupForm" label-width="100px">
          <el-form-item label="分组名称">
            <el-input v-model="groupForm.name" placeholder="请输入分组名称" />
          </el-form-item>
          <el-form-item label="分组描述">
            <el-input
              v-model="groupForm.description"
              type="textarea"
              rows="3"
              placeholder="请输入分组描述"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSaveGroup">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </Layout>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import Layout from "@/components/Layout.vue";

interface CustomerGroup {
  id: number;
  name: string;
  count: number;
  description: string;
}

interface Customer {
  id: number;
  name: string;
  phone: string;
  memberLevel: string;
  totalAmount: number;
  orderCount: number;
  registerTime: string;
}

// 分组列表（模拟数据）
const groupList = ref<CustomerGroup[]>([
  {
    id: 1,
    name: "全部客户",
    count: 58,
    description: "所有注册客户",
  },
  {
    id: 2,
    name: "新注册客户",
    count: 12,
    description: "最近30天内注册的客户",
  },
  {
    id: 3,
    name: "高价值客户",
    count: 8,
    description: "累计消费金额超过5000元的客户",
  },
  {
    id: 4,
    name: "流失风险客户",
    count: 15,
    description: "超过90天未下单的客户",
  },
  {
    id: 5,
    name: "生日客户",
    count: 5,
    description: "本月过生日的客户",
  },
]);

// 当前选中的分组ID
const activeGroupId = ref(1);

// 当前选中的分组
const currentGroup = computed(() => {
  return groupList.value.find((group) => group.id === activeGroupId.value);
});

// 搜索表单
const searchForm = reactive({
  name: "",
  phone: "",
});

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 数据加载状态
const loading = ref(false);

// 客户列表数据（模拟数据）
const customerList = ref<Customer[]>([
  {
    id: 1,
    name: "张三",
    phone: "13812345678",
    memberLevel: "VIP1",
    totalAmount: 1234.56,
    orderCount: 5,
    registerTime: "2023-01-10",
  },
  {
    id: 2,
    name: "李四",
    phone: "13987654321",
    memberLevel: "VIP2",
    totalAmount: 3456.78,
    orderCount: 8,
    registerTime: "2023-02-15",
  },
  {
    id: 3,
    name: "王五",
    phone: "13566778899",
    memberLevel: "VIP3",
    totalAmount: 6789.12,
    orderCount: 12,
    registerTime: "2023-03-20",
  },
]);

// 对话框相关
const dialogVisible = ref(false);
const dialogType = ref("add");
const groupForm = reactive({
  id: 0,
  name: "",
  description: "",
});

// 初始化数据
onMounted(() => {
  fetchCustomerList();
});

// 获取客户列表（模拟数据）
const fetchCustomerList = async () => {
  loading.value = true;
  try {
    // 模拟API请求延迟
    await new Promise((resolve) => setTimeout(resolve, 500));

    // 这里应该是实际的API调用
    // const response = await CustomerService.getCustomersByGroup({
    //   groupId: activeGroupId.value,
    //   page: currentPage.value,
    //   pageSize: pageSize.value,
    //   ...searchForm
    // });

    // customerList.value = response.data;
    // total.value = response.total;

    // 模拟总数据量
    total.value = currentGroup.value?.count || 0;
  } catch (error) {
    console.error("获取客户列表失败:", error);
    ElMessage.error("获取客户列表失败，请稍后重试");
  } finally {
    loading.value = false;
  }
};

// 选择分组
const handleSelectGroup = (index: string) => {
  activeGroupId.value = parseInt(index);
  currentPage.value = 1;
  fetchCustomerList();
};

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1;
  fetchCustomerList();
};

// 重置搜索条件
const resetSearch = () => {
  searchForm.name = "";
  searchForm.phone = "";
  handleSearch();
};

// 处理分页大小变化
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  fetchCustomerList();
};

// 处理页码变化
const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  fetchCustomerList();
};

// 新增分组
const handleAddGroup = () => {
  dialogType.value = "add";
  groupForm.id = 0;
  groupForm.name = "";
  groupForm.description = "";
  dialogVisible.value = true;
};

// 编辑分组
const handleEditGroup = () => {
  if (!currentGroup.value) return;

  dialogType.value = "edit";
  groupForm.id = currentGroup.value.id;
  groupForm.name = currentGroup.value.name;
  groupForm.description = currentGroup.value.description;
  dialogVisible.value = true;
};

// 删除分组
const handleDeleteGroup = () => {
  if (!currentGroup.value) return;

  ElMessageBox.confirm(
    `确定要删除分组"${currentGroup.value.name}"吗？`,
    "提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(() => {
      // 这里应该调用删除API
      // await CustomerService.deleteGroup(currentGroup.value.id);

      // 模拟删除
      const index = groupList.value.findIndex(
        (group) => group.id === currentGroup.value?.id
      );
      if (index !== -1) {
        groupList.value.splice(index, 1);
        ElMessage.success("删除成功");

        // 删除后选中第一个分组
        if (groupList.value.length > 0) {
          activeGroupId.value = groupList.value[0].id;
        }

        fetchCustomerList();
      }
    })
    .catch(() => {
      // 取消删除
    });
};

// 保存分组
const handleSaveGroup = () => {
  if (!groupForm.name) {
    ElMessage.warning("请输入分组名称");
    return;
  }

  if (dialogType.value === "add") {
    // 新增
    // 这里应该调用新增API
    // const result = await CustomerService.createGroup(groupForm);

    // 模拟新增
    const newId = Math.max(...groupList.value.map((group) => group.id)) + 1;
    groupList.value.push({
      id: newId,
      name: groupForm.name,
      description: groupForm.description,
      count: 0,
    });

    ElMessage.success("新增成功");
  } else {
    // 编辑
    // 这里应该调用编辑API
    // await CustomerService.updateGroup(groupForm.id, groupForm);

    // 模拟编辑
    const group = groupList.value.find((group) => group.id === groupForm.id);
    if (group) {
      group.name = groupForm.name;
      group.description = groupForm.description;
    }

    ElMessage.success("编辑成功");
  }

  dialogVisible.value = false;
};

// 从分组中移除客户
const handleRemoveFromGroup = (row: Customer) => {
  if (!currentGroup.value) return;

  ElMessageBox.confirm(
    `确定要将客户"${row.name}"从分组"${currentGroup.value.name}"中移除吗？`,
    "提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(() => {
      // 这里应该调用移除API
      // await CustomerService.removeFromGroup(currentGroup.value.id, row.id);

      // 模拟移除
      const index = customerList.value.findIndex(
        (customer) => customer.id === row.id
      );
      if (index !== -1) {
        customerList.value.splice(index, 1);

        // 更新分组计数
        if (currentGroup.value) {
          currentGroup.value.count--;
        }

        ElMessage.success("移除成功");
      }
    })
    .catch(() => {
      // 取消移除
    });
};
</script>

<style scoped>
.customer-groups-container {
  padding: 20px;
}

.box-card {
  margin-bottom: 20px;
  height: calc(100vh - 140px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.group-list {
  margin-top: 10px;
}

.group-menu {
  border-right: none;
}

.group-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.group-count {
  color: #999;
  font-size: 12px;
}

.search-bar {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
